<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us">
<head>
  <link href="//gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta name="generator" content="Hugo 0.69.0" />

  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>自定义验证码 &middot; 宋申奥的博客</title>

  
  <link type="text/css" rel="stylesheet" href="/hugo_blog/css/print.css" media="print">
  <link type="text/css" rel="stylesheet" href="/hugo_blog/css/poole.css">
  <link type="text/css" rel="stylesheet" href="/hugo_blog/css/syntax.css">
  <link type="text/css" rel="stylesheet" href="/hugo_blog/css/hyde.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Abril+Fatface|PT+Sans:400,400i,700">


  
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/apple-touch-icon-144-precomposed.png">
  <link rel="shortcut icon" href="/favicon.png">

  
  
</head>

  <body class="theme-base-0f ">
  <aside class="sidebar">
  <div class="container sidebar-sticky">
    <div class="sidebar-about">
      <a href="/hugo_blog/"><h1>宋申奥的博客</h1></a>
      <p class="lead">
       这里是宋申奥的个人博客 
      </p>
    </div>

    <nav>
      <ul class="sidebar-nav">
        <li><a href="/hugo_blog/">Home</a> </li>
        
      </ul>
    </nav>

    <p>&copy; 2020. All rights reserved. </p>
  </div>
</aside>

    <main class="content container">
    <div class="post">
  <h1>自定义验证码</h1>
  <time datetime=2020-04-26T10:59:06&#43;0800 class="post-date">Sun, Apr 26, 2020</time>
  <h1 id="自定义验证码">自定义验证码</h1>
<pre><code>#自定义图片验证码
class MyCode(View):

	#定义rgb随机颜色
	def get_random_color(self):

		R = random.randrange(255)
		G = random.randrange(255)
		B = random.randrange(255)

		return (R,G,B)

	#定义图片视图
	def get(self,request):
		#画布
		img_size = (120,50)
		#定义图片对象
		image = Image.new('RGB',img_size,'white')
		#定义画笔
		draw = ImageDraw.Draw(image,'RGB')
		source = '0123456789abcdefghijk'
		#接收容器
		code_str = ''
		#进入循环绘制
		for i in range(4):
			#获取字母颜色
			text_color = self.get_random_color()
			#获取随机下标
			tmp_num = random.randrange(len(source))
			#随机字符串
			random_str = source[tmp_num]
			#装入容器
			code_str += random_str
			#绘制字符串
			draw.text((10+30*i,20),random_str,text_color)
		#获取缓存区
		buf = io.BytesIO()
		#将临时图片保存到缓冲
		image.save(buf,'png')
		#保存随机码
		r.set('code',code_str)
		#保存session
		request.session['code'] = code_str

		print(r.get('code'))

		return HttpResponse(buf.getvalue(),'image/png')
</code></pre><p><img src="/hugo_blog/0d8a90abc2d78eaa5e01d3fb7f57e6da.jpg" alt="每日一图"></p>

</div>


    </main>

    
  </body>
</html>
